<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { postLogin } from '@/apis/apis.js'
import { useUserStore } from '@/stores/stores.js'

const form = ref({
  name: '',
  password: ''
})
const rules = ref({
  name: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入用户名'
    },
    {
      min: 2,
      max: 10,
      trigger: 'blur',
      message: '请输入用户名（长度为2-10个字符）'
    }
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入密码'
    }
  ]
})
const formRef = ref(null)
const userStore = useUserStore()
const router = useRouter()

const handleLogin = () => {
  formRef.value.validate(async (isValid) => {
    if (isValid) {
      const res = await postLogin(form.value)
      if (!res.status) {
        ElMessage({ type: 'info', message: res.msg })
      }
      else {
        userStore.updateUser(res.data)
        ElMessage({ type: 'success', message: res.msg })
        router.push('/home')
      }
    }
  })
}
</script>

<template>
  <div class="view">
    <div class="view-container">
      <div class="view-container-title">后台管理系统</div>
      <div class="view-container-form">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item prop="name">
            <el-input prefix-icon="User" v-model.trim="form.name" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" show-password prefix-icon="Lock" v-model.trim="form.password" />
          </el-form-item>
          <el-form-item>
            <el-button class="login" type="primary" @click="handleLogin">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.view {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;

  .view-container {
    width: 380px;
    height: 240px;
    box-shadow: #409EFF 0px 0px 30px 0px;

    .view-container-title {
      padding: 20px 0;
      text-align: center;
      color: #409EFF;
      font-size: 24px;
      font-weight: bold;
    }

    .view-container-form {
      .el-form {
        margin: 0 auto;
        width: 85%;

        .login {
          width: 100%;
        }
      }
    }
  }
}
</style>
